package com.ffggffgfv.backend.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Logger;

/**
 * AES加密解密工具类
 * 优化加密算法，使结果更紧凑
 */
public class AESUtil {
    // 使用128位密钥，加密结果更短
    private static final String KEY = "1234567890ABCDEF";
    private static final String ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final Logger logger = Logger.getLogger(AESUtil.class.getName());

    /**
     * 加密
     *
     * @param data 明文
     * @return 密文，Base64编码
     */
    public static String encrypt(String data) {
        try {
            if (data == null) {
                return null;
            }

            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedData);
        } catch (Exception e) {
            logger.warning("AES加密异常: " + e.getMessage());
            throw new RuntimeException("AES加密异常", e);
        }
    }

    /**
     * 解密
     *
     * @param encryptedData Base64编码的密文
     * @return 明文，解密失败则返回原始值
     */
    public static String decrypt(String encryptedData) {
        try {
            if (encryptedData == null || encryptedData.isEmpty()) {
                return encryptedData;
            }

            // 检查是否为有效的Base64编码
            if (!isBase64(encryptedData)) {
                logger.warning("无效的Base64编码: " + encryptedData);
                return encryptedData;
            }

            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            byte[] decodedData = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedData = cipher.doFinal(decodedData);
            return new String(decryptedData, StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.warning("AES解密异常: " + e.getMessage() + ", 数据: " + encryptedData);
            return encryptedData; // 解密失败时返回原始值，而不是抛出异常
        }
    }

    /**
     * 检查字符串是否是有效的Base64编码
     *
     * @param input 待检查的字符串
     * @return 是否是有效的Base64编码
     */
    private static boolean isBase64(String input) {
        try {
            // 尝试解码，如果异常则不是有效Base64
            Base64.getDecoder().decode(input);
            // 检查长度是否为4的倍数（考虑到可能有填充）
            return input.length() % 4 == 0 || (input.length() % 4 == 2) || (input.length() % 4 == 3);
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
}
